/**
 * @Title: StockServiceImpl.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @author 张鑫
 * @phone 17561783855
 * @date 2019年4月15日
 */
package com.fortune.rainshineservice.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.base.ParmsModel;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.ProductModel;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.service.StockModel;
import com.fortune.rainshinecommon.model.service.StockRecordsModel;
import com.fortune.rainshinecommon.query.StockQuery;
import com.fortune.rainshinecommon.util.StringUtil;
import com.fortune.rainshineservice.mapper.ProductMapper;
import com.fortune.rainshineservice.mapper.ShopMapper;
import com.fortune.rainshineservice.mapper.StockMapper;
import com.fortune.rainshineservice.mapper.StockRecordsMapper;
import com.fortune.rainshineservice.service.StockService;
import com.google.common.collect.Lists;

/**
 * @author 张鑫
 * @ClassName: StockServiceImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @phone 17561783855
 * @date 2019年4月15日
 */
@Service
public class StockServiceImpl implements StockService {
    private static final Logger logger = LoggerFactory.getLogger(ShopServiceImpl.class);

    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private StockRecordsMapper stockRecordsMapper;
    @Autowired
    private ShopMapper shopMapper;


    @Override
    @Transactional
    public MsgModel addOrUpdate(StockModel stockModel) {
        try {
            int res = 0;
            stockModel.setUpdateId(stockModel.getUser().getUserId());
            Wrapper<StockModel> wrapper = new EntityWrapper<>();
            wrapper.eq("product_id", stockModel.getProductId());
            wrapper.eq("shop_id", stockModel.getShopId());
            List<StockModel> stockList = Optional.ofNullable(stockMapper.selectList(wrapper)).orElse(Lists.newArrayList());

            if (!stockList.isEmpty()) {
                int productAmount = stockList.get(0).getProductAmount();
                //增加
                if (stockModel.getMethod() == 1) {
                    productAmount = stockList.get(0).getProductAmount() + stockModel.getProductAmount();
                }
                //减少
                else if (stockModel.getMethod() == 2) {
                    if (stockList.get(0).getProductAmount() >= stockModel.getProductAmount()) {
                        productAmount = stockList.get(0).getProductAmount() - stockModel.getProductAmount();
                    } else {
                        return new MsgModel("超过库存数量", ResultCode.FAILURE);
                    }
                }
                stockList.get(0).setProductAmount(productAmount);
                res = stockMapper.updateById(stockList.get(0));
            } else {
                stockModel.setCreateId(stockModel.getUser().getUserId());
                res = stockMapper.insert(stockModel);
            }

            if (res > 0) {
                return new MsgModel("库存修改成功！", ResultCode.SUCCESS);
            } else {
                return new MsgModel("库存修改失败！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("addOrUpdate ====> {}", e);
            return new MsgModel("库存修改失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel getStockByShopId(String shopId) {
        try {
            List<StockModel> stocks = new ArrayList<>();
            ShopModel shop = shopMapper.selectById(shopId);
            int count = 0;
            if (shop != null) {
                //若为总店，加载所有展示产品
                if (shop.getShopLevel() == 1) {
                    Wrapper<ProductModel> productWrapper = new EntityWrapper<>();
                    productWrapper.eq("sale_status", 1);
                    List<ProductModel> list = Optional.ofNullable(productMapper.selectList(productWrapper)).orElse(Lists.newArrayList());
                    if (!list.isEmpty()) {
                        for (ProductModel item : list) {
                            StockModel stock1 = new StockModel();
                            stock1.setProductId(item.getId());
                            stock1.setShopId(Integer.valueOf(shopId));
                            StockModel stock2 = stockMapper.selectOne(stock1);
                            if (stock2 == null) {
                                stock2 = stock1;
                                stock2.setProductAmount(0);
                                stock2.setWarningNum(0);
                                stock2.setId(0);
                            }
                            stock2.setProduct(item);
                            stocks.add(stock2);
                        }
                        count = list.size();
                    }
                } else {//招商加盟店库存方法
                    Wrapper<StockModel> wrapper = new EntityWrapper<>();
                    wrapper.eq("shop_id", shopId);
                    stocks = Optional.ofNullable(stockMapper.selectList(wrapper)).orElse(Lists.newArrayList());
                    if (!stocks.isEmpty()) {
                        for (StockModel item : stocks) {
                            ProductModel product = productMapper.selectById(item.getProductId());
                            item.setProduct(product);
                        }
                        count = stocks.size();
                    }
                }
            }
            return new MsgModel(count, stocks);
        } catch (Exception e) {
            logger.error("getStockByShopId ====> {}", e);
            return new MsgModel("获取库存详情失败！", ResultCode.FAILURE);
        }
    }

    @Override
    @Transactional
    public boolean warning(StockModel model) {
        int res = 0;
        if (model.getId() == 0) {
            model.setCreateId(model.getUser().getUserId());
            res = stockMapper.insert(model);
        } else {
            res = stockMapper.updateById(model);
        }
        return res > 0;
    }

    @Override
    @Transactional
    public MsgModel purchase(StockModel model) {
        try {
            int resNum = model.getPurchaseNum();
            if (model.getId() != 0) {
                StockModel stock = stockMapper.selectById(model.getId());
                if (stock != null) {
                    StockRecordsModel record = new StockRecordsModel(stock.getProductId(), stock.getShopId(), stock.getId(), model.getPurchaseNum());
                    //增加库存
                    if (model.getMethod() == 1) {
                        resNum = stock.getProductAmount() + model.getPurchaseNum();
                        record.setType(1);
                    }
                    //减少库存
                    else if (model.getMethod() == 2) {
                        if (model.getPurchaseNum() <= stock.getProductAmount()) {
                            resNum = stock.getProductAmount() - model.getPurchaseNum();
                            record.setType(2);
                        } else {
                            return new MsgModel("操作失败，库存余量不够，请先补充库存！", ResultCode.FAILURE);
                        }
                    }
                    model.setProductAmount(resNum);
                    //更新库存
                    stockMapper.updateById(model);
                    //插入库存记录
                    stockRecordsMapper.insert(record);
                    return new MsgModel("修改库存成功", ResultCode.SUCCESS);
                }
            } else {
                if (model.getMethod() == 1) {
                    if(model.getShopId() == null){
                        //参数没有商铺id时，直接放置总店id
                        model.setShopId(1);
                    }
                    model.setProductAmount(model.getPurchaseNum());
                    if (stockMapper.insert(model) > 0) {
                        Wrapper<StockModel> wrapper = new EntityWrapper<>();
                        wrapper.eq("product_id", model.getProductId());
                        wrapper.eq("shop_id", model.getShopId());

                        StockModel stock = stockMapper.selectList(wrapper).get(0);
                        StockRecordsModel record = new StockRecordsModel(model.getProductId(), model.getShopId(), stock.getId(), model.getPurchaseNum());
                        record.setType(1);
                        //插入库存记录
                        stockRecordsMapper.insert(record);
                        return new MsgModel("修改库存成功", ResultCode.SUCCESS);
                    } else {
                        return new MsgModel("修改库存失败", ResultCode.FAILURE);
                    }
                }
                //减少库存
                else if (model.getMethod() == 2) {
                    return new MsgModel("操作失败，库存余量不够，请先补充库存！", ResultCode.FAILURE);
                }
            }
        } catch (Exception e) {
            logger.error("purchase ====> {}", e);
            return new MsgModel("库存操作失败！", ResultCode.FAILURE);
        }
        return new MsgModel("修改库存成功", ResultCode.SUCCESS);
    }

    @Override
    public List<StockRecordsModel> findDetailStocks(String id) {
        List<StockRecordsModel> records = new ArrayList<>();
        try {
            records = stockRecordsMapper.selectRecordsList(id);
        } catch (Exception e) {
            logger.error("findDetailStocks ====>{}", e);
        }
        return records;
    }

    @Override
    public MsgModel getStockList(ParmsModel parms) {
        try {
            if (parms.getShopId() == null) {
                return new MsgModel("编码不能为空！", ResultCode.FAILURE);
            }
            ShopModel shop = shopMapper.selectById(parms.getShopId());
            if (shop == null) {
                return new MsgModel("仓库不存在！", ResultCode.FAILURE);
            }
            List<StockModel> stocks = Lists.newArrayList();
            int count = 0;
            //若为总店，加载所有展示产品
            if (shop.getShopLevel() == 1) {
                Wrapper<ProductModel> productWrapper = new EntityWrapper<>();
                productWrapper.eq("sale_status", 1);
                if (StringUtils.isNotBlank(parms.getSearchValue())) {
                    productWrapper.like("product_name", parms.getSearchValue());
                }
                if(parms.getPage() == null){
                    parms.setPage(1);
                    parms.setLimit(1000);
                }
                Page<ProductModel> page = new Page<>(parms.getPage(), parms.getLimit());
                List<ProductModel> list = Optional.ofNullable(productMapper.selectPage(page,productWrapper)).orElse(Lists.newArrayList());
                if (!list.isEmpty()) {
                    stocks = list.stream().map(e -> {
                        StockModel stock1 = new StockModel();
                        stock1.setProductId(e.getId());
                        stock1.setShopId(parms.getShopId());
                        StockModel stock2 = stockMapper.selectOne(stock1);
                        if (stock2 == null) {
                            stock2 = stock1;
                            stock2.setProductAmount(0);
                            stock2.setWarningNum(0);
                            stock2.setId(0);
                        }
                        stock2.setProduct(e);
                        return stock2;
                    }).collect(Collectors.toList());
                }
                count = list.size();
                return new MsgModel(count, stocks);
            } else {
//                Wrapper<StockModel> wrapper = new EntityWrapper<>();
//                if (StringUtils.isNotBlank(parms.getSearchValue())) {
//                    Wrapper<ProductModel> pWrapper = new EntityWrapper<>();
//                    pWrapper.eq("sale_status", 1);
//                    pWrapper.like("product_name", parms.getSearchValue());
//                    List<ProductModel> pList = Optional.ofNullable(productMapper.selectList(pWrapper)).orElse(Lists.newArrayList());
//                    if (pList.isEmpty()) {
//                        return new MsgModel(count, stocks);
//                    }
//                    wrapper.eq("shop_id", parms.getShopId());
//                    List<Integer> pIds = pList.stream().map(ProductModel::getId).collect(Collectors.toList());
//                    wrapper.in("product_id", pIds);
//                } else {
//                    wrapper.eq("shop_id", parms.getShopId());
//                }
//                Page<StockModel> page = new Page<>(parms.getPage(), parms.getLimit());
//                stocks = Optional.ofNullable(stockMapper.selectPage(page,wrapper)).orElse(Lists.newArrayList());
//                if (!stocks.isEmpty()) {
//                    stocks.forEach(e -> {
//                        ProductModel product = productMapper.selectById(e.getProductId());
//                        e.setProduct(product);
//                    });
//                    count = stocks.size();
//                }
                Map<String,Object> m = new HashMap<>();
                m.put("shopId",parms.getShopId());
                Page<StockModel> page = new Page<>(parms.getPage(),parms.getLimit());
                List<StockModel> sList = Optional.ofNullable(stockMapper.getSaleStatusList(m, page)).orElse(Lists.newArrayList());
                if(!sList.isEmpty()){
                    sList.forEach(e -> {
                        ProductModel product = productMapper.selectById(e.getProductId());
                        e.setProduct(product);
                    });
                }
                page.setRecords(sList);
                return new MsgModel(page.getRecords().size(), page.getRecords());
            }

        } catch (Exception e) {
            logger.error("getStockList ====>{}", e);
            return new MsgModel("获取库存列表异常！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel stockRecordDetail(ParmsModel parm) {
        Wrapper<StockRecordsModel> wrapper = new EntityWrapper<>();
        if (StringUtil.isNotBlank(parm.getSearchKey())) {
            wrapper.like(parm.getSearchKey(), parm.getSearchValue());
        }
        wrapper.eq("stock_id", parm.getType());
        Page<StockRecordsModel> orderPage = new Page<>(parm.getPage(), parm.getLimit());
        List<StockRecordsModel> list = Optional.ofNullable(stockRecordsMapper
                .selectPage(orderPage, wrapper.orderBy("create_time", false)))
                .orElse(Lists.newArrayList());
        if(!list.isEmpty()){
            list.forEach(e->e.setProductName(productMapper.getNameById(e.getProductId())));
        }
        int total = stockRecordsMapper.selectCount(wrapper);
        return new MsgModel(total, list);
    }

    @Override
    public MsgModel getStocksForShopSale(String shopId) {
        try {
            List<StockModel> stocks = Optional.ofNullable(stockMapper.getStocksForShopSale(shopId)).orElse(Lists.newArrayList());
            if (!stocks.isEmpty()) {
                stocks.forEach(e->{
                    ProductModel product = Optional.ofNullable(productMapper.selectById(e.getProductId())).orElse(new ProductModel());
                    if(product.getIsSale() == 1) {
                        e.setProduct(product);
                    }
                });
            }
            return new MsgModel(ResultCode.SUCCESS, stocks);
        } catch (Exception e) {
            logger.error("getStocksForShopSale ====>{}", e);
            return new MsgModel("获取店铺销售库存列表异常！", ResultCode.FAILURE);
        }

    }

    @Override
    public MsgModel getStocksForShopUse(String shopId) {
        try {
            List<StockModel> stocks = Optional.ofNullable(stockMapper.getStocksForShopUse(shopId)).orElse(Lists.newArrayList());
            if (!stocks.isEmpty()) {
                stocks.forEach(e->{
                    ProductModel product = Optional.ofNullable(productMapper.selectById(e.getProductId())).orElse(new ProductModel());
                    e.setProduct(product);
                });
            }
            return new MsgModel(ResultCode.SUCCESS, stocks);
        } catch (Exception e) {
            logger.error("getStocksForShopUse ====>{}", e);
            return new MsgModel("获取店铺领用库存列表异常！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel getSaleList(StockQuery query) {
        try{
            if(query.getShopId() == null){
                return new MsgModel("门店不能为空！", ResultCode.FAILURE);
            }
            if(query.getPage() == null){
                return new MsgModel("页码不能为空！", ResultCode.FAILURE);
            }
            if(query.getLimit() == null){
                return new MsgModel("条数不能为空！", ResultCode.FAILURE);
            }
            Map<String,Object> m = new HashMap<>();
            m.put("shopId",query.getShopId());
            if(StringUtils.isNotBlank(query.getProductName())){
                m.put("productName", query.getProductName());
            }
            Page<StockModel> page = new Page<>(query.getPage(),query.getLimit());
            List<StockModel> list = Optional.ofNullable(stockMapper.getSaleList(m, page)).orElse(Lists.newArrayList());
            if(!list.isEmpty()){
                list.forEach(e->{
                    ProductModel product = Optional.ofNullable(productMapper.selectById(e.getProductId())).orElse(new ProductModel());
                    e.setProduct(product);
                });
            }
            page.setRecords(list);
            return new MsgModel(page.getRecords().size(), page.getRecords());
        }catch (Exception e){
            logger.error("getSaleList ====>{}", e);
            return new MsgModel("获取销售产品列表异常！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel getConsumeList(StockQuery query) {
        try{
            if(query.getShopId() == null){
                return new MsgModel("门店不能为空！", ResultCode.FAILURE);
            }
            if(query.getPage() == null){
                return new MsgModel("页码不能为空！", ResultCode.FAILURE);
            }
            if(query.getLimit() == null){
                return new MsgModel("条数不能为空！", ResultCode.FAILURE);
            }
            Map<String,Object> m = new HashMap<>();
            m.put("shopId",query.getShopId());
            if(StringUtils.isNotBlank(query.getProductName())){
                m.put("productName", query.getProductName());
            }
            Page<StockModel> page = new Page<>(query.getPage(),query.getLimit());
            List<StockModel> list = Optional.ofNullable(stockMapper.getConsumeList(m, page)).orElse(Lists.newArrayList());
            if(!list.isEmpty()){
                list.forEach(e->{
                    ProductModel product = Optional.ofNullable(productMapper.selectById(e.getProductId())).orElse(new ProductModel());
                    e.setProduct(product);
                });
            }
            page.setRecords(list);
            return new MsgModel(page.getRecords().size(), page.getRecords());
        }catch (Exception e){
            logger.error("getConsumeList ====>{}", e);
            return new MsgModel("获取领用产品列表异常！", ResultCode.FAILURE);
        }
    }
}
